package com.rtsapp.server.benchmark.script;

import com.rtsapp.server.benchmark.script.*;
import java.io.IOException;
import java.util.*;

/**
 * 脚本生成
 *
 * TODO 这个类需要移动到rtsserver中, 脚本的生成和解析是对应的，应该放在同一个地方
 */
public class ScriptGenerator {


    private final  ScriptAnalyze analyze = new ScriptAnalyze();



    public void generator( String testScriptDestDir,  String[] logFiles,  Set<Integer> extractUserIds, IScriptCommandFactory factory, ICaseHelper caseHelper, ScriptGeneratorTemplate template ) throws IOException {

        Map<Integer, List<ScriptCommand>> commandMap = new HashMap<>();
        for( String logFile : logFiles ){
            analyze.parse( logFile, factory, extractUserIds, commandMap );
        }

        Map<String,Object> context = new HashMap<>();

        for( Integer playerId : commandMap.keySet() ){

            String saveFileTemplate;
            if( testScriptDestDir.endsWith( "/" ) ){
                saveFileTemplate = testScriptDestDir + playerId + "_case_%d.xml";
            }else{
                saveFileTemplate = testScriptDestDir + "/" + playerId + "_case_%d.xml";
            }

            List< List<ReqInfo> > sessionList  =  caseHelper.parseReqPairs( commandMap.get( playerId ) );

            for( int i = 0; i < sessionList.size(); i++ ) {

                String saveFile = String.format( saveFileTemplate, i );
                context.clear();
                context.put("commandList",  sessionList.get( i ) );
                context.put("helper", caseHelper);

                template.generateFromTemplate(saveFile, context);
            }
        }
    }


    public void generatorList( String testScriptDestDir,  String[] logFiles,  Set<Integer> extractUserIds,  IScriptCommandFactory factory, ICaseHelper caseHelper, ScriptGeneratorTemplate template ) throws IOException {

        List<ScriptCommand> commandMap = new ArrayList<>();
        for( String logFile : logFiles ){
            analyze.parseList(logFile, factory, extractUserIds, commandMap);
        }

        String saveFileTemplate;
        if( testScriptDestDir.endsWith( "/" ) ){
            saveFileTemplate = testScriptDestDir +  "case_all.xml";
        }else{
            saveFileTemplate = testScriptDestDir + "/" +  "case_all.xml";
        }

        Map<String,Object> context = new HashMap<>();
        context.put( "commandList", commandMap );
        context.put("helper", caseHelper);

        template.generateFromTemplate( saveFileTemplate, context );
    }


}
